package channelService

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"go-fox-edge-channel-tcp-server/channelEngine/channelManager"
	"go-fox-edge-channel-tcp-server/channelService/reportService"
	"sync"
)

type channelService struct {
	channelName2ServiceKey sync.Map
}

func (e *channelService) OpenChannel(channelName string, channelParam map[string]interface{}) error {
	serviceKey := Map.GetString(channelParam, "serviceKey", "")
	if serviceKey == "" {
		return errors.New("通道的配置参数不能为空: serviceKey")
	}

	e.channelName2ServiceKey.Store(channelName, serviceKey)

	return nil
}

func (e *channelService) CloseChannel(channelName string, channelParam map[string]interface{}) error {
	e.channelName2ServiceKey.Delete(channelName)
	return nil
}

func (e *channelService) Publish(requestVO *commRedisRpc.ChannelRequestVO) error {
	val, ok := e.channelName2ServiceKey.Load(requestVO.Name)
	if !ok {
		return errors.New("参数不能为空: serviceKey")
	}
	serviceKey := val.(string)

	ctx := channelManager.GetContextByServiceKey(serviceKey)
	if ctx == nil {
		return errors.New("找不到对应的socket连接: " + requestVO.Name + ", 出错原因-> 远端设备尚未主动连接或者未登陆认证serviceKey信息")
	}

	return publish.publish(ctx, requestVO)
}

func (e *channelService) Report() ([]*commRedisRpc.ChannelRespondVO, error) {
	return reportService.PopAll()
}
